package com.note.es.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.note.es.connection.ESConnection;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: DocumentUtil
 * @Description: 文档相关操作
 */
public class DocumentUtil {

    private static final Logger logger = LoggerFactory.getLogger(DocumentUtil.class);

    /**
     * 批量索引
     *
     * @param indexName
     * @param type
     * @param sources
     */
    public boolean bulkInsert(String indexName, String type, List<Map<String, Object>> sources) {
        boolean isSuccess = false;
        BulkRequest bulkRequest = new BulkRequest();
        for (Map<String, Object> source : sources) {
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.index(indexName);
            indexRequest.type(type);
            indexRequest.source(source);
            indexRequest.id((String) source.get("id"));
            bulkRequest.add(indexRequest);
        }
        try {
            BulkResponse bulkResponse = ESConnection.getClient().bulk(bulkRequest, RequestOptions.DEFAULT);
            if (!bulkResponse.hasFailures()) {
                isSuccess = true;
            } else {
                logger.error("批量索引有失败，具体消息：{}", bulkResponse.buildFailureMessage());
            }
        } catch (IOException e) {
            logger.error("issues: ", e);
        }
        return isSuccess;
    }

    /**
     * 批量修改
     *
     * @param indexName
     * @param type
     * @param idsAndDocs
     */
    public boolean bulkUpdate(String indexName, String type, JSONArray idsAndDocs) {
        boolean isSuccess = false;
        BulkRequest bulkRequest = new BulkRequest();
        for (Object obj : idsAndDocs) {
            JSONObject idAndDoc = (JSONObject) obj;
            UpdateRequest updateRequest = new UpdateRequest();
            updateRequest.index(indexName);
            updateRequest.type(type);
            updateRequest.id(idAndDoc.getString("uuid"));
            updateRequest.doc(idAndDoc.getJSONObject("doc"));
            bulkRequest.add(updateRequest);
        }
        try {
            BulkResponse bulkResponse = ESConnection.getClient().bulk(bulkRequest, RequestOptions.DEFAULT);
            if (!bulkResponse.hasFailures()) {
                isSuccess = true;
            } else {
                logger.error("批量更新有失败，具体消息{}", bulkResponse.buildFailureMessage());
            }
        } catch (IOException e) {
            logger.error("issues: ", e);
        }
        return isSuccess;
    }

}
